package fun.tan90.easy.binlog.plugin.mysql.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import fun.tan90.easy.binlog.plugin.common.service.PluginService;
import fun.tan90.easy.binlog.plugin.mysql.model.MysqlClientParams;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;

/**
 * description TODO
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2023/11/15 14:41
 */
@Slf4j
public class MysqlPluginService implements PluginService {

    @Override
    public boolean test(String params) {
        MysqlClientParams mysqlClientParams = JSONUtil.toBean(params, MysqlClientParams.class);

        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(StrUtil.format("jdbc:mysql://{}/{}", mysqlClientParams.getJdbcUrl(), mysqlClientParams.getDatabaseName()));
        config.setUsername(mysqlClientParams.getUsername());
        config.setPassword(mysqlClientParams.getPassword());

        config.setMaximumPoolSize(mysqlClientParams.getMaxPoolSize());
        config.setMinimumIdle(mysqlClientParams.getMinIdle());

        try (HikariDataSource hikariDataSource = new HikariDataSource(config)) {
            Connection connection = hikariDataSource.getConnection();
            connection.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("mysql 连接测试失败，{}", e.getMessage());
            return false;
        }
    }
}
